package com.tchepannou.limbe.interceptor;

import com.tchepannou.limbe.Controller;
import com.tchepannou.limbe.Interceptor;
import com.tchepannou.limbe.Service;

import javax.inject.Inject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * User: herve
 * Date: 14-04-05 6:55 AM
 */
public class InjectInterceptor implements Interceptor
{
    @Override
    public int before(Controller controller)
    {
        Field[] fields = controller.getClass().getDeclaredFields();
        for (Field field : fields)
        {
            field.setAccessible(true);
            if (field.getAnnotation(Inject.class) != null)
            {
                try
                {
                    inject(field, controller);
                }
                catch (IllegalAccessException e)
                {
                    throw new RuntimeException("Unable to inject: " + controller + "->" + field.getName(), e);
                }
            }
        }
        return Interceptor.CONTINUE;
    }

    @Override
    public void after(Controller controller)
    {

    }

    @Override
    public int before(Method method, Controller controller)
    {
        return Interceptor.CONTINUE;
    }

    @Override
    public void after(Method method, Controller controller, Throwable e)
    {

    }

    private void inject (Field field, Controller controller)
            throws IllegalAccessException
    {
        Class type = field.getType();
        if (Service.class.isAssignableFrom(type))
        {
            Service service = controller.getContext().findService(type);
            field.set(controller, service);
        }
    }
}
